#pragma once
#include <iostream>
#include <cstring>
#include <functional>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <pthread.h>
#include "Log.hpp"
#include "InetAddr.hpp"
#include "ThreadPool.hpp"


const int gport = 8888;
const int gsockfd = -1;
const static int gblcklog=8;
enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR,
    LISTEN_ERROR
};

using task_t =std::function<void()>;
class TcpServer
{
public:
    TcpServer( uint16_t port = gport)
        : _listensockfd(gsockfd),
          _port(port),
          _isrunning(false)
    {
    }
    void InitServer()
    {
        // 1.创建socket
        _listensockfd = ::socket(AF_INET, SOCK_STREAM, 0);
        if (_listensockfd < 0)
        {
            LOG(FATAL, "socket create error\n");
            exit(LISTEN_ERROR);
        }

        // 2. 绑定
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        if (::bind(_listensockfd, (struct sockaddr *)&local, sizeof(local))<0)
        {
            LOG(FATAL, "bind error\n");
            exit(BIND_ERROR);
        }
        LOG(DEBUG, " bind success \n");

        if(::listen(_listensockfd,gblcklog)<0)
        {
            LOG(FATAL,"listen error \n");
            exit(-1);
        }
        LOG(DEBUG,"listen success\n");
    }
    class ThreadData
    {
    public:
        int _sockfd;
        TcpServer *_self;
        InetAddr _addr;

    public:
        ThreadData(int sockfd, TcpServer *self, const InetAddr &addr)
            : _sockfd(sockfd),
              _self(self),
              _addr(addr)
        {
        }
    };
    void Loop()
    {
        _isrunning = true;
        while (_isrunning)
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            int sockfd = ::accept(_listensockfd, (struct sockaddr *)&client, &len);
            std::cout<<sockfd<<std::endl;
            if (sockfd < 0)
            {
                LOG(WARNING, "accept error\n");
                continue;
            }
            InetAddr addr(client);
            LOG(INFO, "get a new link ,client info : %s ,sockfd is: %d \n", addr.AddrStr().c_str(), sockfd);

            // version 0
            // Service(sockfd, addr);

            // version 1 多进程版本
            // pid_t id=fork()
            // {
            //     if(id==0)
            //     {
            //         //child 
            //         if(fork()>0) eixt(0);

            //         Service(sockfd,addr);
            //         exit(0);
            //     }
            //     //father
            //     ::close(sockfd);
            //     int n=waitpid(id,nullptr,0);
            //     if(n>0)
            //     LOG(INFO,"wait child success\n");
            // }

            // version 2  多线程版本
            // pthread_t tid;
            // ThreadData*td=new ThreadData(sockfd,this,addr);
            // pthread_create(&tid,nullptr,Excute,td);

            // version 3 线程池版本
            task_t t=std::bind(&TcpServer::Service,this,sockfd,addr);
            ThreadPool<task_t>::GetInstance()->Equeue(t);

        }

        _isrunning = false;
    }
    static void * Excute(void*args)
    {
        pthread_detach(pthread_self());
        ThreadData*td=static_cast<ThreadData*>(args);
        td->_self->Service(td->_sockfd,td->_addr);
        delete td;
        return nullptr;
    }

    void Service(int sockfd, InetAddr addr)
    {
        while (true)
        {
            char buffer[1024];
            ssize_t n = ::read(sockfd, buffer, sizeof(buffer) - 1);
            if (n > 0)
            {
                buffer[n] = 0;
                LOG(INFO, "get message from client %s , message %s \n", addr.AddrStr().c_str(), buffer);

                std::string echo_string = "[server echo ]#";
                echo_string += buffer;
                write(sockfd, echo_string.c_str(), echo_string.size());
            }
            else if (n == 0)
            {
                LOG(INFO, "client %s quit \n", addr.AddrStr().c_str());
                break;
            }
            else 
            {
                LOG(ERROR,"read error");
                break;
            }
        }
        ::close(sockfd);
    }
    ~TcpServer() {}

private:
    int _listensockfd;
    uint16_t _port;

    bool _isrunning;
};
